<?php
include('../Misc/DatabaseConnection.php');
include('../Misc/Settings.php');

class UserRegHandler
{

	private $db = NULL;
	public function __construct()
	{
		$database = new DatabaseConnection(Settings::DbSettings());
		$database->Connect();
		$this->db = $database;
	}

	function RegisterUser($username, $password, $email)
	{
		//kryptera password med md5 + hash 'sha512'.. Lösen blir 128 tecken i databasen
		$password = md5($password);
		//$password = hash('sha512', $password);

		if($stmt = $this->db->getPrepareStatement("INSERT INTO players (Username, Password, Email) VALUES(?, ?, ?)"))
    	{
    		$stmt->bind_param("sss", $username, $password, $email);
    		if($stmt->execute())
    		{
    			$stmt->close();
    			return true;
    		}
    	}
    		return false;
	}

	//icke implementerat ännu
	function DoesNameExist($username) 
	{	
		if ($stmt = $this->db->getPrepareStatement("SELECT * FROM players WHERE Username = ?")) 
		{
			//$stmt->bind_param("isss", $id, $username, $password, $email);
			$stmt->bind_param("s", $username);
		    /* execute query */
		    $stmt->execute();
		
		    $stmt->bind_result($id, $username, $password, $email);
		 	while ($stmt->fetch()) 
		 	{
		 		//Om id är mer än 0 så finns användaren
			 	if($id > 0)
				{
					//echo $username;
					return true;
				}
				else
				{
					return false;
				}
		    }
		    /* close statement */
		    $stmt->close();
	}   }

	//Kollar om längen på lösenordet är korrekt minst 6 tecken
	function PasswordCorrectLength($password)
	{
		if(strlen($password) >= 6)
	    {
	    	return true;
	    }
	    elseif(strlen($password) < 6)
	    {
	    	return false;
	    }
	}
	
	//Kollar om lösenorden matchar
	function PasswordMatch($p1, $p2)
	{	
		if($p1 == $p2)
	    {
	    	return true;
	    }
	    else
	    {
	    	return false;
	    }
	}

	//Kollar om epost matchar
	function EmailMatch($e1, $e2)
	{	
		if($e1 == $e2)
	    {
	    	return true;
	    }
	    else
	    {
	    	return false;
	    }
	}
}